import usePlanningStore from "@/stores/planningStore";
const planningStore = usePlanningStore();
import dayjs from "dayjs";

const generateTimeSlots = () => {
  const timeSlots = [];

  planningStore.timeRanges.forEach((content) => {
    const { startDate, endDate, startTime, endTime, granularity } = content;

    // 组合开始日期和时间
    const [startHour, startMinute] = startTime.split(":").map(Number);
    const startDateTime = new Date(startDate);
    startDateTime.setHours(startHour, startMinute, 0, 0);

    // 组合结束日期和时间
    const [endHour, endMinute] = endTime.split(":").map(Number);
    const endDateTime = new Date(endDate);
    endDateTime.setHours(endHour, endMinute, 0, 0);

    let currentFrom = new Date(startDateTime);

    // 循环生成时间槽，直到超过结束时间
    while (currentFrom < endDateTime) {
      const currentTo = new Date(
        currentFrom.getTime() + granularity * 60 * 1000
      );

      // 如果当前时间槽的结束时间超过了总的结束时间，则停止生成
      if (currentTo > endDateTime) {
        break;
      }

      // 格式化时间字符串
      const formatTime = (date) => {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, "0");
        const day = String(date.getDate()).padStart(2, "0");
        const hours = String(date.getHours()).padStart(2, "0");
        const minutes = String(date.getMinutes()).padStart(2, "0");
        const seconds = String(date.getSeconds()).padStart(2, "0");
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      };

      timeSlots.push({
        from: formatTime(currentFrom),
        to: formatTime(currentTo),
        duration: granularity,
        seats: [],
      });

      // 移动到下一个时间槽的开始时间
      currentFrom = currentTo;
    }
  });

  timeSlots.sort((a, b) => dayjs(a.from).valueOf() - dayjs(b.from).valueOf());
  planningStore.timeSlots = timeSlots;
  if (!timeSlots.length) {
    ElMessage.error("请先添加值班时段");
    return false;
  }
  return timeSlots;
};

export default generateTimeSlots;
